package alpaca.textprocessor;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 
 *
 */

public class URLTextProcessor implements ITextProcessor {
	/*
	 * Original: ^(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]
	 * Source: http://stackoverflow.com/questions/163360/regular-expresion-to-match-urls-java
	 * 
	 * http:// is a requirement
	 * 
	 * Modified: (@)?(https?)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|] 
	 */
	
	/*
	 * Original: (@)?(href=\")?(http://)?[A-Za-z-]+(\\.[\\w-]+)+(/[&\\n=?\\+\\%/\\.\\w]+)?
	 * Source: http://www.coderanch.com/t/382015/java/java/regex-find-url
	 * 
	 * http:// is optional
	 * 
	 * Modified: (@)?(href=\")?(http://)?[www]+(\\.[\\w-]+)+(/[&\\n=?\\+\\%/\\.\\w]+)?
	 */
	
	private static final String REGEXP_HTTP_REQUIREMENT = "(@)?(https?)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]";
	private static final String REGEXP_HTTP_OPTIONAL = "(@)?(href=\")?(http://)?[www]+(\\.[\\w-]+)+(/[&\\n=?\\+\\%/\\.\\w]+)?";

	@Override
	public String modifyText(String text) {
		StringBuffer result = new StringBuffer();
		
		Matcher m = null;
		Pattern p = null;
		Replacement replace = null;
		
		if(includesHTTP(text)){
			p = Pattern.compile(REGEXP_HTTP_REQUIREMENT);
			replace = new Replacement() {
				@Override
				public String getReplacement(Matcher matcher) {
					return "<a href=\"" + matcher.group(0) + "\">" + matcher.group(0) + "</a>";
				}
			};
		}
		else {
			p = Pattern.compile(REGEXP_HTTP_OPTIONAL);
			replace = new Replacement() {
				@Override
				public String getReplacement(Matcher matcher) {
					return "<a href=\"http://" + matcher.group(0) + "\">" + matcher.group(0) + "</a>";
				}
			};
		}
		
		m = p.matcher(text);
		
	    while(m.find()) {
	    	m.appendReplacement(result, replace.getReplacement(m));
	    }
	    
	    m.appendTail(result);
	    return result.toString();
	  }

	  private boolean includesHTTP(String text){
		  Pattern p = Pattern.compile(REGEXP_HTTP_REQUIREMENT);
		  Matcher m = p.matcher(text);
		  return m.find();
	  }
	  
	  private interface Replacement {
		  String getReplacement(Matcher matcher);
	  }
}

